// src/composables/useToast.ts
import { ref, computed, reactive, inject, provide } from 'vue';
import { showToast, showLoading, hideLoading } from '@tarojs/taro';

export type ToastOptions = {
  title?: string;
  icon?: 'success' | 'loading' | 'none';
  image?: string;
  duration?: number;
  mask?: boolean;
};

/**
 * 全局 Toast 提示函数
 * @returns 
 */
export function useToast() {
  // 显示加载提示
  const loading = (title = '加载中...', options: Omit<ToastOptions, 'title' | 'icon'> = {}) => {
    showLoading({
      title,
      mask: true,
      ...options,
      icon: 'loading'
    });
  };

  // 显示成功提示
  const success = (title = '成功', options: Omit<ToastOptions, 'title' | 'icon'> = {}) => {
    showToast({
      title,
      duration: 1500,
      mask: true,
      ...options,
      icon: 'success'
    });
  };

  // 显示失败提示
  const error = (title = '失败', options: Omit<ToastOptions, 'title' | 'icon'> = {}) => {
    showToast({
      title,
      duration: 1500,
      mask: true,
      ...options,
      icon: 'none'
    });
  };

  // 显示普通提示
  const show = (title: string, options: Omit<ToastOptions, 'title'> = {}) => {
    showToast({
      title,
      duration: 1500,
      mask: true,
      ...options
    });
  };

  // 清除所有提示
  const clear = () => {
    hideLoading();
  };

  return {
    loading,
    success,
    error,
    show,
    clear
  };
}

/**
 * 创建 Toast 上下文，用于在组件外部调用
 */
export function createToastContext() {
  const toast = useToast();
  provide('toast', toast);
  return toast;
}

/**
 * 在组件外部使用 Toast
 */
export function useGlobalToast() {
  return inject('toast') as ReturnType<typeof useToast>;
}    